const App = getApp();
import {
    url
} from '../../../../modelApi/url_config.js'
Page({
    data: {
        goodsId: "", //商品id
        show: true,
        goodsDetail: {}, //商品
        statusBarHeight: "",
        statusBarPadding: "",
        productImglist: [],
        desc: '',
        shopcartCount: 0,
        RecShopParams: {
            "isRec": 1,
            "pageNo": 1,
            "pageSize": 10
        }, //推荐列表参数
        RecShopList: [], //推荐列表 
        hadNumberData: null, //获得手机
        hasuserInfo: false,
        showShareBool: false,
        maskHidden: false,
        qrcodeImg: '',
        productImgTempFilePath: '', // 海报产品本地图片
        qrcodeImgOBJtempFilePath: '',// 小程序本地图片
        avatartempFilePath: '', // 头像本地图片
    },
    onLoad: function (options) {
        let goodID= ''
        if (options.scene) {
            const scene = decodeURIComponent(options.scene)
            goodID = scene.split('&')[1]
            wx.setStorageSync('shareUserId', scene.split('&')[0])
        } else {
            options.shareUserId && wx.setStorageSync('shareUserId', options.shareUserId)
        }
        this.setData({
            statusBarPadding: App.globalData.navTop,
            statusBarHeight: App.globalData.navHeight,
            goodsId: goodID || options.goodsId,
            hadNumberData: wx.getStorageSync('tel') ? wx.getStorageSync('tel') : null
        });
        this.getGoodsDetailFun(this.data.goodsId);
        this.loadRecShop();
        this.getQrcode()
        // 判断是否用户授权
        wx.getSetting({
            success: (res) => {
                this.setData({
                    hasuserInfo: res.authSetting['scope.userInfo'] && res.errMsg === "getSetting:ok"
                })
            }
        })
    },
    onShow() {
        this.geCartListFun();
    },
	saveImgFunc() {
		wx.saveImageToPhotosAlbum({
			filePath: this.data.imagePath,
			success(res) {}
		})
	},
    /* 分享 */
	toggleShareModal: function () {
		this.setData({
			showShareBool: !this.data.showShareBool,
        });
    },
    downfiletempPr0() {
        const that = this;
        const imgUrl = this.data.productImglist[0]
        // 主图海报
		wx.downloadFile({
			url: imgUrl,
			success(res) {
				if (res.statusCode === 200) {
                    that.setData({
                        productImgTempFilePath: res.tempFilePath
                    })
				}
			}
        })
    },
    downfiletemp() {
        const that = this;
        // 小程序码
		wx.downloadFile({
			url: that.data.qrcodeImg,
			success(qrcodeImgOBJ) {
				if (qrcodeImgOBJ.statusCode === 200) {
					that.setData({
                        qrcodeImgOBJtempFilePath: qrcodeImgOBJ.tempFilePath
                    })
				}
			}
        })
        // 头像
		wx.downloadFile({
			url: wx.getStorageSync('avatar'),
			success(res) {
				if (res.statusCode === 200) {
					that.setData({
                        avatartempFilePath: res.tempFilePath
                    })
				}
			}
		})
    },
    creatBanner() {
        var that = this;
		this.setData({
			maskHidden: false,
			showShareBool: false
		});
		wx.showToast({
			title: '图片生成中...',
			icon: 'loading',
			duration: 500
		});
		setTimeout(function () {
			wx.hideToast()
			that.createNewImg();
			that.setData({
				maskHidden: true
			});
		}, 500)
    },
	getQrcode() {
        let shareUserId = null
        if (wx.getStorageSync('isMember')) {
            shareUserId = wx.getStorageSync('userId');
        } else {
            shareUserId = wx.getStorageSync('shareUserId') || '';
        }
		const params = {
			page: 'pages/index/sonpages/goods-detail/index',
			scene: `${shareUserId}&${this.data.goodsId}`,
			isHyaline: true,
			width: '280'
		}
		App.ajax(url.getQrcode, params, 'post').then(res => {
            if (+res.code === 0) {
                this.setData({
                    qrcodeImg: res.data
                })
                this.downfiletemp()
            }
		})
	},
    //处理文字多出省略号显示
    dealWords(options) {
        options.ctx.setFontSize(options.fontSize);//设置字体大小
        var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);//实际总共能分多少行
        var count = allRow >= options.maxLine ? options.maxLine : allRow;//实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
        var endPos = 0;//当前字符串的截断点
        for (var j = 0; j < count; j++) {
            var nowStr = options.word.slice(endPos);//当前剩余的字符串
            var rowWid = 0;//每一行当前宽度    
            if (options.ctx.measureText(nowStr).width > options.maxWidth) {//如果当前的字符串宽度大于最大宽度，然后开始截取
                for (var m = 0; m < nowStr.length; m++) {
                    rowWid += options.ctx.measureText(nowStr[m]).width;//当前字符串总宽度
                    if (rowWid > options.maxWidth) {                        
                        if (j === options.maxLine - 1) { //如果是最后一行
                            options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 18);    //(j+1)*18这是每一行的高度        
                        } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 18);
                        }
                        endPos += m;//下次截断点
                        break;
                    }
                }
            } else {//如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
            }
        }
    },
	createNewImg: function () {
		var that = this;
        var context = wx.createCanvasContext('mycanvas');
		// 背景
		context.setFillStyle("#fff")
		context.fillRect(0, 0, 400, 600)
		// 主图海报
		context.drawImage(this.data.productImgTempFilePath, 0, 0, 400, 320);
		context.setFontSize(16);
        context.setFillStyle('#333333');
        const goodsTitletext = this.data.goodsDetail.goodsTitle
        this.dealWords({
            ctx: context,//画布上下文
            fontSize: 16,//字体大小
            word: goodsTitletext ,//需要处理的文字
            maxWidth: 360,//一行文字最大宽度
            x: 20,//文字在x轴要显示的位置
            y: 340,//文字在y轴要显示的位置
            maxLine: 2//文字最多显示的行数
        })
        context.stroke();
		// 绘制名字
		context.setFontSize(14);
		context.setFillStyle('#333333');
		context.fillText(wx.getStorageSync('nickName'), 74, 558);
        context.stroke();
        // 绘制价格
		context.setFontSize(14);
		context.setFillStyle('red');
		context.fillText(`热销价：￥${this.data.goodsDetail.price}`, 20, 400);
        context.stroke();
        context.setFontSize(14);
		context.setFillStyle('#999');
		context.fillText(`购买可省￥${this.data.goodsDetail.savemoney}`, 20, 420);
        context.stroke();
		// 长按识别
		context.setFontSize(16);
		context.setFillStyle('#999999');
		context.fillText('长按图片识别产品', 256, 570);
		context.stroke();
		// 小程序码
		context.drawImage(this.data.qrcodeImgOBJtempFilePath, 252, 410, 128, 128);
        // 头像
        context.save()
        context.beginPath()
        context.arc(40, 554, 20, 0, 2 * Math.PI)
        context.clip();
        context.drawImage(this.data.avatartempFilePath, 20, 534, 40, 40);
		context.draw();
		//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
		setTimeout(function () {
			wx.canvasToTempFilePath({
				canvasId: 'mycanvas',
				success: function (res) {
					wx.hideToast()
					var tempFilePath = res.tempFilePath;
					that.setData({
						imagePath: tempFilePath,
						canvasHidden: true
					});
				},
				fail: function (res) {
					console.log(res);
				}
			});
		},100);
	},
    closeShareFunc() {
		this.setData({
			showShareBool: false
		})
    },
	cancelImgFunc() {
		this.setData({
			maskHidden: false
		})
	},
    onPageScroll: function (t) {
        this.setData({
            show: t.scrollTop <= 0 ? true : false
        })
    },
    parserich(details) {
        details = details.replace(/\<p/gi, '<P class="rich-p" ');
        details = details.replace(/\<h2/gi, '<P class="rich-h"');
        var texts = '';//待拼接的内容
        while (details.indexOf('<img') != -1) {//寻找img 循环
            texts += details.substring('0', details.indexOf('<img') + 4);//截取到<img前面的内容
            details = details.substring(details.indexOf('<img') + 4);//<img 后面的内容
            if (details.indexOf('style=') != -1 && details.indexOf('style=') < details.indexOf('>')) {
                texts += details.substring(0, details.indexOf('style="') + 7) + "width:100%;max-width:100%;height:auto;display:block";//从 <img 后面的内容 截取到style= 加上自己要加的内容
                details = details.substring(details.indexOf('style="') + 7); //style后面的内容拼接
            } else {
                texts += ' style="width:100%;max-width:100%;height:auto;display:block" ';
            }
        }
        texts += details;//最后拼接的内容
        return texts
    },
    /* 获取详情数据 */
    getGoodsDetailFun: function (data) {
        let params = {
            goodsId: data
        }
        App.ajax(url.goodsDetailUrl, params, 'get').then(res => {
            const desc = this.parserich(res.data.description);
            const savemoney = App.sub(res.data.marketPrice, res.data.price)
            res.data.savemoney = savemoney
            this.setData({
                goodsDetail: res.data,
                productImglist: res.data.picList.split(","),
                desc: desc
            })
            this.downfiletempPr0()
        })
    },
    bindgetuserinfo(e) {
        if (e.detail.errMsg === 'getUserInfo:ok') {
            this.addShopCarFun()
        }
    },
    addShopCarFun() {
        App.ifLogin(() => {
            this.setData({
                hasuserInfo: true
            })
        })
    },
    addcart() {
        let params = {
            goodsId: this.data.goodsId,
            number: 1
            // skuId: this.data.goodsId
        }
        App.ajax(url.addShopCar, params, 'post').then(res => {
            this.goCart()
        })
    },
    /* 获取购物车列表 */
    geCartListFun() {
        App.ajax(url.cartList, {}, 'get').then(res => {
            this.setData({
                shopcartCount: res.data.length
            })
        })
    },
    /* 获取为你推荐 */
    loadRecShop() {
        App.ajax(url.goodsListUrl, this.data.RecShopParams, 'post').then(res => {
            this.setData({
                RecShopList: res.rows
            })
        })
    },
    linkToSearch: function () {
        wx.navigateTo({
            url: "/pages/index/sonpages/search/index"
        });
    },
    goback: function () {
        1 === getCurrentPages().length ? wx.switchTab({
            url: "/pages/index/index"
        }) : wx.navigateBack();
    },
    goHome() {
        wx.switchTab({
            url: '/pages/index/index'
        })
    },
    goCart() {
        wx.navigateTo({
            url: '/pages/cart/index'
        })
    },
    goOrder() {
        wx.navigateTo({
            url: '/pages/mine/sonpages/order/orderSettlement/index'
        })
    },
    onShareAppMessage(res) {
        let url_data = "";
        if (wx.getStorageSync('isMember')) {
            url_data = `pages/index/sonpages/goods-detail/index?shareUserId=${wx.getStorageSync('userId')}&goodsId=${this.data.goodsId}`;
        } else {
            url_data = wx.getStorageSync('shareUserId') != '' ?  
                `pages/index/sonpages/goods-detail/index?shareUserId=${wx.getStorageSync('shareUserId')}&goodsId=${this.data.goodsId}` : `pages/index/sonpages/goods-detail/index?goodsId=${this.data.goodsId}`;
        }
        return {
            title: this.data.goodsDetail.goodsTitle,
            path: url_data,
            imageUrl: this.data.productImglist[0]
        }
    },
    /* 获取手机号 */
    getPhoneNumber: function (e) {
        const that = this;
        const type = e.currentTarget.dataset.type
        if (e.detail.errMsg = "getPhoneNumber:ok") {
            const param = {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv,
            };
            App.ajax(url.wxDecodePhoneUrl, param, 'post').then(res => {
                wx.setStorageSync("tel", res.data.purePhoneNumber)
                if (+type === 2) {
                    this.addcart()
                }
                that.setData({
                    hadNumberData: res.data.purePhoneNumber
                })
            })
        }
    },
});